package com.lej.dataservice.club.http

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import com.google.gson.JsonObject
import com.lej.core.base.app
import com.lej.core.base.currentActivity
import com.lej.core.common.ERROR_CODE
import com.lej.core.router.CRouter
import com.lej.core.router.CRouter.Companion.navigation
import com.lej.core.utils.extention.toast
import com.lej.dataservice.club.data.PengRepository
import com.lej.dataservice.club.http.coupons.CouponsReward
import com.lej.dataservice.club.http.rx.CustomNetworkException
import com.lej.theme.dialog.CustomAlertPopDialog
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

suspend fun <T> BaseResponse<T>.checkData(): T = kotlin.run {
    gold_popup?.let { CouponsReward.reward(it) }
    checkError(code, message) { result }
}

suspend fun <T> BaseListRes<T>.checkList(): MutableList<T>? = kotlin.run {
    gold_popup?.let { CouponsReward.reward(it) }
    checkError(code, message) { result?.list }
}

/**
 * 内部数据为空的返回值做数据校验
 */
//suspend fun BaseResponse<*>.checkEmptyData() {
//    VipStateRepository.setVIP(login_svip)//设置vip等级
//
//    if (gold_popup != null) {
//        CouponsReward.reward(gold_popup)
//    }
//
//    checkError(code, message) { }
//}

suspend fun JsonObject.checkToken(): String? {
    val code = this["code"].asInt
    val message = this["msg"].asString ?: "未知错误"
    return checkError(code, message) { this["qiniutoken"].asString }
}

suspend inline fun <R> checkError(code: Int, message: String?, block: () -> R): R {
    when (code) {
        RESULT_SUCCESS -> return block()
        LOGIN_ERROR -> CRouter.login.navigation { withInt(ERROR_CODE, code) }
        404, 500 -> { //资源不可用、目标不存在、其他错误
        }
        BLACKLIST -> CRouter.login.navigation { withInt(ERROR_CODE, code) }//受限用户,不可登录(封号等情况)

        FACE_UN_PASS -> errorWarning(message, feedbackInCancelBtn = false) {//真人审核未通过,跳转人脸识别
            CRouter.face.navigation { withInt(ERROR_CODE, code) }
        }
        FACE_UN_CHECK -> errorWarning(message, hideCancel = false) {//真人审核未通过,跳转人脸识别
            CRouter.face.navigation { withInt(ERROR_CODE, code) }
        }
        HEAD_UN_PASS -> errorWarning(message) {//头像审核未通过,跳转设置头像
            CRouter.head.navigation { withInt(ERROR_CODE, code) }
        }
        HEAD_UN_CHECK -> errorWarning(message) {//头像未上传,跳转设置头像
            CRouter.head.navigation { withInt(ERROR_CODE, code) }
        }
        CARD_UN_PASS -> errorWarning(message) {//证件审核未通过,跳转重新上传
            CRouter.studentCard.navigation { withInt(ERROR_CODE, code) }
        }
        REMOTE_LOGIN -> CRouter.login.navigation { withInt(ERROR_CODE, code) }//其他设备抢登,跳转到登录页面
    }
    throw CustomNetworkException(code, message)
}

suspend fun feedbackCopy() {
    PengRepository().getPubNum()?.let { pubNum ->
        val cm = app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        cm.setPrimaryClip(ClipData.newPlainText("Peng公众号", pubNum))
        "复制公众号（${pubNum}）成功".toast()
    }
    accountErrorPopUp?.dismiss()
}

///緩存一下當前彈窗，避免彈多個
var accountErrorPopUp: BasePopupView? = null
suspend fun errorWarning(
    message: String?,
    feedbackInCancelBtn: Boolean = false,
    hideCancel: Boolean = !feedbackInCancelBtn,
    confirm: () -> Unit
) {
    ///在展示了就不管了
    //先延迟200毫秒，避免同时两个请求完成，展示两个弹窗
    delay(200)
    if (accountErrorPopUp?.isShow == true)
        return
    suspendCoroutine<Boolean> {
        accountErrorPopUp = XPopup.Builder(currentActivity)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(true)
            .autoDismiss(false)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView) {
                    super.onDismiss(popupView)
                    accountErrorPopUp = null
                }
            }).asCustom(
                CustomAlertPopDialog(
                    currentActivity!!,
                    title = "提示",
                    content = message,
                    confirmText = "去认证",
                    cancelText = if (feedbackInCancelBtn) "去反馈" else "取消",
                    hideCancel = hideCancel,
                    cancel = {
                        if (feedbackInCancelBtn)
                            GlobalScope.launch {
                                feedbackCopy()
                                it.resume(true)
                            }
                        else {
                            it.resume(true)
                        }
                    },
                    onConfirm = {
                        confirm.invoke()
                        it.resume(false)
                    }
                )
            )
            .show()
        accountErrorPopUp?.show()
    }
}

val Throwable.handleCode
    get() = if (this is CustomNetworkException) this.code
    else ExceptionHandle.handleException(this).code

val Throwable.handleMsg
    get() = if (this is CustomNetworkException) this.message
    else ExceptionHandle.handleException(this).message ?: this.javaClass.name


val Throwable.handleCustomMsg
    get() = if (this is CustomNetworkException) this.message
    else null
